#include "ask_mpeg_encode.h"
#include "ask_mpeg_frames.h"


void write_ask_mpeg_to_file(FILE *fh,u_int8_t *bytes,int length)
{
	// first write a couple of frames of silence, as early frames in layer 1 get corrupted
	for(int i=0;i<4;i++) fwrite(mpeg_frames[0x1000],1,FRAME_SIZE,fh);

	// then write "01" 126 times, for sync
	for(int i=0;i<21;i++) fwrite(mpeg_frames[0xaaa],1,FRAME_SIZE,fh);

	if(length==0) // special case for 0 bytes which is pretty useless
	{
		// write 4+256+4 0 bits
		for(int i=0;i<22;i++) fwrite(mpeg_frames[0],1,FRAME_SIZE,fh);
		return;
	}

	// write 0000 followed by the first byte
	fwrite(mpeg_frames[bytes[0]<<4],1,FRAME_SIZE,fh);

	// handle as many of the rest of the bytes as possible in chunks of three
	u_int8_t *ptr=bytes+1;
	for(int i=0;i<(length-1)/3;i++)
	{
		// first byte, the four low bits of the second
		fwrite(mpeg_frames[ptr[0]|((ptr[1]&0x0f)<<8)],1,FRAME_SIZE,fh);
		// high bits of second byte, then third
		fwrite(mpeg_frames[((ptr[1]&0xf0)>>4)|(ptr[2]<<4)],1,FRAME_SIZE,fh);

		ptr+=3;
	}

	// handle remaining bytes
	switch(length%3)
	{
		case 1: // all bytes sent
			// 256+8 0 bits
			for(int i=0;i<22;i++) fwrite(mpeg_frames[0],1,FRAME_SIZE,fh);
		break;

		case 2: // one byte left
			// last byte followed by 4 0 bits
			fwrite(mpeg_frames[ptr[0]],1,FRAME_SIZE,fh);
			// 252 0 bits
			for(int i=0;i<21;i++) fwrite(mpeg_frames[0],1,FRAME_SIZE,fh);
		break;

		case 0: // two bytes left
			// next-to-last byte, the four low bits of the last
			fwrite(mpeg_frames[ptr[0]|((ptr[1]&0x0f)<<8)],1,FRAME_SIZE,fh);
			// high bits of last byte, then 0000000
			fwrite(mpeg_frames[(ptr[1]&0xf0)>>4],1,FRAME_SIZE,fh);
			// 248+4 0 bits
			for(int i=0;i<21;i++) fwrite(mpeg_frames[0],1,FRAME_SIZE,fh);
		break;
	}

	fputc(0,fh); // end marker?
}

// start: 126 0-1 bits, 4 0 bits.
// => 21 010101010101 frames, then 0000+first byte

// bulk: three bytes in two frames
// a0a1a2a3a4a5a6a7 b0b1b2b3b4b5b6b7 c0c1c2c3c4c5c6c7
// a0a1a2a3a4a5a6a7b0b1b2b3 b4b5b6b7c0c1c2c3c4c5c6c7
//  0 1 2 3 4 5 6 7 8 9 a b  0 1 2 3 4 5 6 7 8 9 a b

// end: 256 0 bits
